package cn.kgc.tangcco.http;

import cn.hutool.core.date.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/10/13 下午2:26
 */
@WebServlet(urlPatterns = "/requestLine")
public class RequestLine extends HttpServlet {
    private static final long serialVersionUID = -4589371062257538043L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求方式
        System.out.println("请求方式：" + request.getMethod());

        // 获取路径(URL、URI)
        System.out.println("请求的URL：" + request.getRequestURL());
        System.out.println("请求的URI：" + request.getRequestURI());

        // 协议
        System.out.println("获取的是使用的协议：" + request.getProtocol());
        System.out.println("获取的是协议的名称：" + request.getScheme());

        // 获取查询字符串
        System.out.println("请求的查询字符串：" + request.getQueryString());
        Map<String, String> map = parseQueryString(request.getQueryString());
        map.forEach((key ,value ) -> System.out.println("name = " + key + "\tvalue = " + value));

        // 上下文路径
        System.out.println("请求的上下文路径：" + request.getContextPath());
        // ${pageContext.request.contextPath}
    }

    public Map<String, String> parseQueryString(String queryString) {
        Map<String, String> map = new HashMap<>();
        String[] split = queryString.split("&");
        for (String param : split) {
            String[] split1 = param.split("=");
            map.put(split1[0],split1[1]);
        }
        return map;
    }
}
